package com.ocom.webapi.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.excel.EasyExcelUtil;
import com.ocom.common.utils.poi.ExcelUtil;
import com.ocom.common.vo.payconfig.schoolwifiinfo.SchoolWifiInfoVo;
import com.ocom.common.vo.webapi.SchoolWifiPageVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.webapi.feign.HumanClientService;
import com.ocom.webapi.feign.PayConfigClientService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
@Slf4j
public class SchoolWifiPageController {

    @Autowired
    private HumanClientService humanClientService;

    @Autowired
    private PayConfigClientService payConfigClientService;

    @PostMapping(WebApiServiceUrl.Url_SchoolWifiPageOnShow)
    public Result schoolWifiPageOnShow(@RequestBody SchoolWifiInfoVo schoolWifiInfoVo) {

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Long comId = yoCiUser.getComId();
        if (ObjectUtil.isEmpty(schoolWifiInfoVo.getComId())) {
            schoolWifiInfoVo.setComId(Math.toIntExact(comId));
        }
        return payConfigClientService.getSchoolWifiList(schoolWifiInfoVo);
    }

    @PostMapping(WebApiServiceUrl.Url_SchoolWifiPageModify)
    public Result schoolWifiPageModify(@RequestBody SchoolWifiInfoVo schoolWifiInfoVo) {
        log.info("校园WiFi修改{}",schoolWifiInfoVo.toString());
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Long comId = yoCiUser.getComId();
        String username = yoCiUser.getUsername();
        if (ObjectUtil.isEmpty(schoolWifiInfoVo.getComId())) {
            schoolWifiInfoVo.setComId(Math.toIntExact(comId));
        }
        if (ObjectUtil.isNotEmpty(username)) {
            schoolWifiInfoVo.setUpdateUser(username);
        }
        return payConfigClientService.updateSchoolWifiInfo(schoolWifiInfoVo);

    }

    @PostMapping(WebApiServiceUrl.Url_SchoolWifiPageCheckStatus)
    public Result schoolWifiPageCheckStatus(@RequestBody SchoolWifiInfoVo schoolWifiInfoVo) {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Long comId = yoCiUser.getComId();
        String username = yoCiUser.getUsername();
        if (ObjectUtil.isEmpty(schoolWifiInfoVo.getComId())) {
            schoolWifiInfoVo.setComId(Math.toIntExact(comId));
        }
        if (ObjectUtil.isNotEmpty(username)) {
            schoolWifiInfoVo.setUpdateUser(username);
        }
        return payConfigClientService.updateSchoolWifiInfo(schoolWifiInfoVo);
    }

    @PostMapping(WebApiServiceUrl.Url_SchoolWifiPageImport)
    public Result schoolWifiPageImport(@RequestParam Long comId, @RequestPart("file") MultipartFile file) throws Exception {

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
//        Long comId = yoCiUser.getComId();
        String username = yoCiUser.getUsername();
        List<SchoolWifiPageVo> schoolWifiInfoVos = EasyExcelUtil.readFromExcel(file.getInputStream(), SchoolWifiPageVo.class, 0);

        Map<String, Integer> statusMap = new HashMap<>();

        List<SchoolWifiInfoVo> list = schoolWifiInfoVos.stream()
                .filter(Objects::nonNull).map(schoolWifiPageVo -> {
                    SchoolWifiInfoVo schoolWifiInfoVo = new SchoolWifiInfoVo();
                    BeanUtils.copyProperties(schoolWifiPageVo, schoolWifiInfoVo);
                    statusMap.put("待审核", 0);
                    statusMap.put("通过", 1);
                    statusMap.put("不通过", 2);
                    schoolWifiInfoVo.setStatus(statusMap.getOrDefault(schoolWifiPageVo.getStatus(), 0));
                    return schoolWifiInfoVo;
                }).collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        AtomicInteger count = new AtomicInteger();
        list.forEach(schoolWifiInfoVo -> {
            String pName = schoolWifiInfoVo.getPName();
            String pCode = schoolWifiInfoVo.getPCode();
            map.put("pName", pName);
            map.put("pCode", pCode);
            map.put("comId", comId);
            map.put("page",0);
            map.put("size",0);
            Result personInfo = humanClientService.PersonnelGetPersonInfo(map);

            JSONObject jsonObject =JSONObject.parseObject(JSON.toJSONString(personInfo.getData()));
            if(jsonObject.getInteger("total")==0||ObjectUtil.isEmpty(jsonObject.get("list"))) {
                return;
            }
            JSONArray jsonArray = jsonObject.getJSONArray("list");
            if (ObjectUtil.isEmpty(jsonArray)) {
                schoolWifiInfoVo.setPId(Math.toIntExact(jsonObject.getLong("pId")));
                schoolWifiInfoVo.setComId(Math.toIntExact(comId));
                schoolWifiInfoVo.setUpdateUser(username == null ? schoolWifiInfoVo.getUpdateUser() : username);
                payConfigClientService.updateSchoolWifiInfo(schoolWifiInfoVo);
                count.getAndIncrement();
            } else {
                jsonArray.forEach(json -> {
                    JSONObject object = (JSONObject) json;
                    schoolWifiInfoVo.setPId(Math.toIntExact(object.getLong("pId")));
                    schoolWifiInfoVo.setComId(Math.toIntExact(comId));
                    schoolWifiInfoVo.setUpdateUser(username == null ? schoolWifiInfoVo.getUpdateUser() : username);
                    payConfigClientService.updateSchoolWifiInfo(schoolWifiInfoVo);
                    count.getAndIncrement();
                });
            }
        });
        return ResultUtil.success("处理成功人数：" + count.get());
    }

    @GetMapping(WebApiServiceUrl.Url_ExportSchoolWifiPage)
    public void exportSchoolWifiPage(HttpServletResponse response,SchoolWifiInfoVo schoolWifiInfoVo){
        log.info("开始导出校园WIFI 请求参数：{}",schoolWifiInfoVo);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置背景颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        //设置头字体
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)13);
        headWriteFont.setBold(true);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //设置头居中
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);


        String fileName = null;
        try {
            fileName = URLEncoder.encode("校园WIFI", "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setHeader("Content-disposition",fileName + ".xlsx");

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        schoolWifiInfoVo.setComId(Math.toIntExact(yoCiUser.getComId()));
        schoolWifiInfoVo.setPage(0);
        schoolWifiInfoVo.setSize(0);
        Result result = payConfigClientService.getSchoolWifiList(schoolWifiInfoVo);
        ArrayList<SchoolWifiPageVo> arrayList = new ArrayList<>();
        Map<Integer, String> statusMap = new HashMap<>();
        statusMap.put(0, "待审核");
        statusMap.put(1, "通过");
        statusMap.put(2, "不通过");
        if(result.getCode() == 200) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));
            if(ObjectUtil.isEmpty(jsonObject)){
                return;
            }
            JSONArray list = jsonObject.getJSONArray("list");
            if(ObjectUtil.isEmpty(list)){
                return;
            }
                list.forEach(obj -> {
                    SchoolWifiInfoVo schoolWifiInfoVo1 = JSON.parseObject(JSON.toJSONString(obj), SchoolWifiInfoVo.class);
                    SchoolWifiPageVo schoolWifiPageVo = new SchoolWifiPageVo();
                    String status = statusMap.getOrDefault(schoolWifiInfoVo1.getStatus(), "未知状态");
                    schoolWifiPageVo.setStatus(status);
                    schoolWifiPageVo.setRemark(schoolWifiInfoVo1.getRemark());
                    schoolWifiPageVo.setPassword(schoolWifiInfoVo1.getPassword());
                    schoolWifiPageVo.setPName(schoolWifiInfoVo1.getPName());
                    schoolWifiPageVo.setPCode(schoolWifiInfoVo1.getPCode());
                    schoolWifiPageVo.setLoginName(schoolWifiInfoVo1.getLoginName());
                    schoolWifiPageVo.setUserName(schoolWifiInfoVo1.getUserName());
                    arrayList.add(schoolWifiPageVo);
                });
            }
        try {
            EasyExcel.write(response.getOutputStream(), SchoolWifiPageVo.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("校园WIFI").doWrite(arrayList);
        } catch (IOException e) {
            log.info("导出校园WIFI失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}